﻿using Furion;
using Microsoft.AspNetCore.Http;
using System.Security.Claims;

namespace HYHY_Core.Tool.Token
{
    /// <summary>
    /// token工具类
    /// </summary>
    public static class TokenService
    {
        /// <summary>
        /// 获取token信息
        /// </summary>
        /// <returns></returns>
        public static ClaimKeys GetClaimKey()
        {
            ClaimKeys claimKey = new();
            var user = App.User;
            if (user != null)
            {
                claimKey.UserId = user.FindFirstValue(nameof(claimKey.UserId)) ?? "";
                claimKey.DataPermissions = user.FindFirstValue(nameof(claimKey.DataPermissions)) ?? "";
                claimKey.UserName = user.FindFirstValue(nameof(claimKey.UserName)) ?? "";
                claimKey.PhoneNumber = user.FindFirstValue(nameof(claimKey.PhoneNumber)) ?? "";
                claimKey.PermissionGroupId = user.FindFirstValue(nameof(claimKey.PermissionGroupId)) ?? "";
                claimKey.UserType = user.FindFirstValue(nameof(claimKey.UserType)) ?? "未登录用户";
            }
            return claimKey;
        }
    }

    /// <summary>
    /// 接口状态码401返回给前端（在Program.cs做为中间件使用）
    /// </summary>
    public class StatusCodeMiddleware
    {
        private readonly RequestDelegate _next;

        public StatusCodeMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            await _next(context); // 调用下一个中间件

            // 检查状态码是否为 401
            if (context.Response.StatusCode == StatusCodes.Status401Unauthorized)
            {
                context.Response.ContentType = "application/json"; // 设置响应内容类型
                //var response = new
                //{
                //    context.Response.StatusCode,
                //    Message = "Token失效，未授权访问" // 自定义消息
                //};

                // 将响应写入上下文
                await context.Response.WriteAsync("StatusCode：401！Token失效，未授权访问，请重新登录");
            }
        }
    }
}
